<?php

namespace app\api\controller\meet;

use app\common\controller\Api;
use app\common\model\meet\CouponTemplate;

class Coupon extends Api
{
    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];

    /**
     * @var CouponTemplate
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

        $this->model = new CouponTemplate();
    }

    public function index()
    {
        $page = $this->request->get('page/d', 1);
        $page_size = $this->request->get('page_size/d', 10);

        $condition = [
            'status' => $this->model::STATUS_NORMAL,
            'end_time' => ['gt', time()],
            'validity_type' => $this->model::VALIDITY_TYPE_TIME
        ];

        $orCondition = [
            'status' => $this->model::STATUS_NORMAL,
            'validity_type' => $this->model::VALIDITY_TYPE_DAYS,
        ];

        $list = $this->model
            ->where(function ($query) use ($condition) {
                $query->where($condition);
            })
            ->whereOr(function ($query) use ($orCondition) {
                $query->where($orCondition);
            })
            ->field('id,name,money,limit,grant_nums,draw_limit,validity_type,validity_days,start_time,end_time,available_type')
            ->order('createtime', 'desc')
            ->paginate(['list_rows' => $page_size, 'page' => $page]);

        foreach ($list as $key => $value) {
            if ($value['validity_type'] == $this->model::VALIDITY_TYPE_TIME) {
                $validity = date('Y-m-d', $value['start_time']) . ' ~ ' . date('Y-m-d', $value['end_time']);
            } else {
                $validity = $value['validity_days'] ? '领取后' . $value['validity_days'] . '天有效' : '未使用前永久有效';
            }

            $range = '';

            if ($value['available_type'] === $this->model::AVAILABLE_TYPE_MALL) {
                $range = '仅限购买商品使用';
            } else if ($value['available_type'] === $this->model::AVAILABLE_TYPE_RESERVATION) {
                $range = '仅限预约使用';
            } else if ($value['available_type'] === $this->model::AVAILABLE_TYPE_ALL) {
                $range = '全场通用';
            }

            $value['range'] = $range;

            $value['draw'] = $value['draw_limit'] > 0 ? '每人仅限领取' . $value['draw_limit'] . '张' : '';

            $value['validity'] = $validity;
        }

        $this->success('', $list);
    }

    public function receive()
    {
        $id = $this->request->post('id/d', 0);

        if (empty($id)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $coupon_template = $this->model->where('id', '=', $id)->find();

        if (empty($coupon_template)) {
            $this->error(__('The coupon does not exist'));
        }

        if ($coupon_template['validity_type'] === $this->model::VALIDITY_TYPE_TIME) {
            if ($coupon_template['end_time'] < time()) {
                $this->error(__('The coupon has expired'));
            }
        }

        if ($coupon_template['draw_limit'] > 0) {
            //已领取数量
            $count = (new \app\common\model\meet\Coupon())->where(['user_id' => $this->auth->id, 'template_id' => $coupon_template['id']])->count();
            if ($count >= $coupon_template['draw_limit']) {
                $this->error(__('You have already received %s coupon and cannot claim it again', $count));
            }
        }

        if ($coupon_template['grant_nums'] >= 0) {
            //已发放数量
            $count = (new \app\common\model\meet\Coupon())->where(['template_id' => $coupon_template['id']])->count();
            if ($count >= $coupon_template['grant_nums']) {
                $this->error(__('Coupons have been distributed'));
            }
        }

        $coupon_model = new \app\common\model\meet\Coupon();

        $data = [
            'user_id' => $this->auth->id,
            'template_id' => $coupon_template['id'],
            'name' => $coupon_template['name'],
            'money' => $coupon_template['money'],
            'limit' => $coupon_template['limit'],
            'get_type' => $coupon_model::GET_TYPE_RECEIVE,
            'available_type' => $coupon_template['available_type'],
            'range_type' => $coupon_template['range_type'],
            'range_goods' => $coupon_template['range_goods'],
            'range_reservation' => $coupon_template['range_reservation'],
            'status' => $coupon_model::STATUS_NOT_USE,
        ];

        if ($coupon_template['validity_type'] == $this->model::VALIDITY_TYPE_DAYS) {
            if ($coupon_template['validity_days'] > 0) {
                $time = time();
                $data['start_time'] = $time;
                $data['end_time'] = $time + 86400 * $coupon_template['validity_days'];
            } else {
                $data['start_time'] = 0;
                $data['end_time'] = 0;
            }
        } else {
            $data['start_time'] = $coupon_template['start_time'];
            $data['end_time'] = $coupon_template['end_time'];
        }

        (new \app\common\model\meet\Coupon())->save($data);

        $this->success(__('Claim successfully'));
    }

    public function userCoupon()
    {
        $page = $this->request->get('page/d', 1);
        $page_size = $this->request->get('page_size/d', 10);
        $status = $this->request->get('status/d', 0);

        $model = new \app\common\model\meet\Coupon();

        if ($status == 2) {
            $condition = [
                'status' => $model::STATUS_USE,
            ];

            $orCondition = [];
        } else {
            $condition = [
                'status' => $model::STATUS_NOT_USE,
                'user_id' => $this->auth->id,
                'end_time' => ['gt', time()],
            ];

            $orCondition = [
                'status' => $model::STATUS_NOT_USE,
                'user_id' => $this->auth->id,
                'end_time' => 0,//无期限
            ];
        }


        $list = $model
            ->where(function ($query) use ($condition) {
                $query->where($condition);
            })
            ->whereOr(function ($query) use ($orCondition) {
                $query->where($orCondition);
            })
            ->order('createtime', 'desc')
            ->paginate(['list_rows' => $page_size, 'page' => $page]);

        if ($list) {
            foreach ($list as $key => $value) {
                $validity = '';

                $range = '';

                if ($value['status'] == $model::STATUS_NOT_USE) {
                    if (!empty($value['start_time'])) {
                        $validity = date('Y-m-d', $value['end_time']) . ' 前有效';
                    } else {
                        $validity = '未使用前永久有效';
                    }
                }

                if ($value['available_type'] === $this->model::AVAILABLE_TYPE_MALL) {
                    $range = '仅限购买商品使用';
                } else if ($value['available_type'] === $this->model::AVAILABLE_TYPE_RESERVATION) {
                    $range = '仅限预约使用';
                } else if ($value['available_type'] === $this->model::AVAILABLE_TYPE_ALL) {
                    $range = '全场通用';
                }

                $value['range'] = $range;

                $value['validity'] = $validity;
            }
        }

        $this->success('', $list);
    }
}
